package com.example.demo.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class InterceptorLogin implements HandlerInterceptor {

    //在请求处理之前进行调用（Controller方法调用之前）
    @Override
    //前置拦截器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //System.out.println("执行了前置拦截器~");

        try {
            //获取登录的session值
            Object userInfo = request.getSession().getAttribute("user");
            if (userInfo != null){
                return true;
            }

            String url = request.getContextPath();
            //System.out.println(url);
            //log.info("请先登录！");

            //用户未登录则回到登录页
            //response.sendRedirect("login");
            response.sendRedirect(url+"login");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }

    //请求处理之后调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //System.out.println("执行了postHandle拦截器~");
    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    //后置拦截器
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //System.out.println("执行了afterCompletion拦截器~");
    }
}
